// miniprogram/pages/deviceControl/tempHumi/index.js
const app = getApp();
const { EventTypes } = require('qcloud-iotexplorer-appdev-sdk').AppDevSdk.constants;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    alarm_temp_max:0,  //温度告警值
    temp_value: 0,  //温度
    humi_value:0,  //湿度
    input_value:'',
    gradientColor: {  //渐变色
      '0%': 'skyblue',
      '100%': '#ee0a24',
    },
    deviceInfo:{},
    deviceId:'',
    AliasName:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      AliasName:options.AliasName
    });
    wx.setNavigationBarTitle({
      title: options.AliasName,
    });
    this.getData();
    this.getDevicedata();
  },

  //获取上一页传递来的数据
  getData:function(){
    let that = this;
    const eventChannel = that.getOpenerEventChannel();
    eventChannel.on('getDeviceData',function(data){
      that.setData({
        deviceInfo:data.data.info
      });
      console.log('deviceInfo:',that.data.deviceInfo);
      that.createWs();
    });
     
  },

  //获取设备物模型数据
  getDevicedata:function(){
    let that = this;
    app.sdk.init().then(()=>{
      app.sdk.requestApi('AppGetDeviceData',{
        ProductId:that.data.deviceInfo.ProductId,
        DeviceName:that.data.deviceInfo.DeviceName 
      })
      .then((res)=>{
        console.log('设备数据',res);
        let data = JSON.parse(res.Data);
        that.setData({
          temp_value:data['temp'].Value,
          humi_value:data['humi'].Value,
          alarm_temp_max:data['alarm_temp_max'].Value
        })
      })
      .catch((err)=>{
        console.log(err);
      })
    })
  },

  //跳转到设备详情页
  goToChooseMore:function(e){
    let that = this;
    wx.navigateTo({
      url: `/pages/deviceInfo/detailInfo/index?AliasName=${that.data.AliasName}`,
      success: (result) => {
         result.eventChannel.emit('getDeviceInfo',{ data:e.currentTarget.dataset });
      },
    })
  },

  //建立长连接通信
  createWs: function(){
    let that = this;
    app.sdk.init().then(()=>{
      let deviceId = [];
      deviceId.push(that.data.deviceInfo.DeviceId);
      console.log('deviceid:',deviceId);
      app.sdk.subscribeDevices(deviceId)
      .then(()=>{
        console.log('已订阅设备信息');
        app.sdk.connectWebsocket()
        .then(()=>{
          console.log('已建立长连接');
          //监听设备数据上报
          app.sdk.on(EventTypes.WsControl,listener1);
          app.sdk.on(EventTypes.WsReport,listener2);
        })
        .catch((err)=>{
          console.log(err);
        });
      })
      .catch((error)=>{
        console.log(error);
      })
    }) 
    const listener1 = ({ deviceId, deviceData }) => {
      console.log('websocket device control', deviceId, deviceData);
      that.setData({
        deviceId:deviceId,
        alarm_temp_max:deviceData['alarm_temp_max'].Value
      })
    };
    const listener2 = ({ deviceId, deviceData }) => {
      console.log('websocket device report', deviceId, deviceData);
      that.setData({
        deviceId:deviceId,
        alarm_temp_max:deviceData['alarm_temp_max'].Value,
        temp_value:deviceData['temp'].Value,
        humi_value:deviceData['humi'].Value
      })
    };
  },

  //输入框输入事件
  onChange(e){
    this.setData({ input_value:e.detail })
  },
 
  //按钮点击提交
  sendChange(){
    let that = this;
    let data = { };
    wx.showLoading({
      title: '正在提交',
      mask: true,
    })
    data.DeviceId = that.data.deviceInfo.DeviceId;
    data.Data=`{\"alarm_temp_max\":${that.data.input_value}}`;
    app.sdk.init().then(()=>{
      app.sdk.requestApi('AppControlDeviceData',data)
      .then((res)=>{
        that.setData({ alarm_temp_max:that.data.input_value });
        console.log(res);
        wx.hideLoading({
          success: () => {
            wx.showToast({
              title: '修改成功',
              mask:true
            })
          },
        })
      })
      .catch((err)=>{
        wx.hideLoading({
          success: () => {
            wx.showToast({
              title: '修改失败',
              icon: 'error',
              mask:true
            })
          },
        })
        console.log(err);
      })
    })
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})